/**
 * Created by xiey on 2016/3/29.
 */
as.directive('fileField', [function () {
    return {
        restrict: 'EA',
        scope   : {},
        require : {
            ngModel: '^^ngModel',
            field  : '^^aField'
        },
        template: function () {
            var content = [];
            content.push('<div class="uploader input-group" ng-class="{active:active}">');
            content.push('  <input type="file" readonly="readonly" name="{{name}}" ng-click="active=true" ng-blur="active=false"/>');
            content.push('  <span class="filename" ng-bind="fileName"></span>');
            content.push('  <span class="action">请选择文件</span>');
            content.push('  <a-loader show="loading" size="mini"></a-loader>');
            content.push('</div>');
            return content.join('');
        },
        link    : function (scope, el, attr, req) {
            var fieldCfg = req.field.getFieldCfg(), $input = el.find('input');
            var reader = new FileReader();
            scope.name = fieldCfg.name;
            scope.fileName = '未选择任何文件';
            reader.addEventListener('loadstart', function () {
                scope.$apply(function () {
                    scope.loading = true;
                });
            }, false);
            reader.addEventListener('load', function () {
                if (reader.readyState === reader.DONE && !reader.error) {
                    req.ngModel.$setViewValue(reader.result);
                }
            }, false);
            reader.addEventListener('loadend', function () {
                scope.$apply(function () {
                    scope.loading = false;
                });
            }, false);
            $input.on('change', function () {
                var file = $input[0].files[0];
                if (file) {
                    scope.fileName = file.name;
                    reader.readAsDataURL(file);// base64: readAsDataURL(); ArrayBuffer: readAsArrayBuffer(); binary: readAsBinaryString;
                } else {
                    scope.fileName = '未选择任何文件';
                    req.ngModel.$setViewValue('');
                }
            });
        }
    };
}]);